<template>
  <div class="login-content">
    <img width="200px" src="./images/loginLogo.png" class="login-pic" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="phone"
        name="phone"
        label="手机号"
        type="number"
        placeholder="请填写手机号"
        :rules="[{ required: true }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="请填写密码"
        :rules="[{ required: true }]"
      />
      <div style="margin-top: 30px">
        <van-button round block type="info" native-type="submit"
          >登录 / 注册</van-button
        >
      </div>
    </van-form>
    <Tabbar />
  </div>
</template>

<script>
import { Toast } from "vant";
import { reqLogin } from "@/api/index";
import jwtdecode from "jwt-decode";
export default {
  data() {
    return {
      phone: "",
      password: "",
    };
  },
  methods: {
    async onSubmit(values) {
      let res = await reqLogin(values);
      if (res.msg === "登录成功") {
        if (res.status === 200) {
          let token = jwtdecode(res.data);
          let obj = {
            phone: token.phone,
            token: res.data,
            id: token.id,
          };
          this.$store.commit("login/setUserInfo", obj);
          localStorage.setItem("userInfo", JSON.stringify(obj));
          Toast("登录成功");
          this.$emit('closeLogin');
          this.$router.go(0);
        } else {
          Toast("登录失败");
        }
      } else if (res.msg === "注册成功") {
        Toast("注册成功，请登录");
      } else {
        Toast("手机号或密码错误");
      }
    },
  }
};
</script>

<style lang="less" scoped>
.login-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30px 0;
}
.login-pic {
  width: 130px;
  height: 130px;
  margin-bottom: 20px;
}
</style>

<style>
.van-button--info {
  background-color: #143ea9;
  border: 1px solid #143ea9;
}
</style>
